﻿using System;
using System.Collections.Generic;
using SqlSugar;
using WebApplication11.Helper;
using WebApplication11.Models;

namespace WebApplication11.Dao;

public class tpDao
{
    public static SqlSugarClient db = dbHelper.CretClient();
    public List<tp> getMsg()
    {
        var list = db.Queryable<park_tree>()
            .LeftJoin<tree>((a, b) => a.TreeId == b.TreeId)
            .LeftJoin<park>((a, b , c) => a.ParkId == c.ParkId)
            .Select((a, b, c)=> new tp
            {
                tree = b.TreeName,
                park = c.ParkName
            })
            .ToList();
        return list;
    }

    public bool delete(String tree, String park)
    {
        //删除中间关系即可(?
        var temp1 = db.Queryable<tree>().Where(it => it.TreeName == tree).ToList();
        int treeId = temp1[0].TreeId;
        var temp2 = db.Queryable<park>().Where(it => it.ParkName == park).ToList();
        int parkId = temp2[0].ParkId;
        try
        {
            db.Deleteable<park_tree>().Where(it =>it.ParkId == parkId && it.TreeId == treeId ).ExecuteCommand();
            return true;
        }  catch (Exception e) {
            return false;
        }
    }

    public bool insert(String tree, String park)
    {
        try
        {
            // 先判断tree - id 是否存在
            if (db.Queryable<tree>().Where(it => it.TreeName == tree).ToList().Count == 0)
            {
                db.Insertable(new tree()
                {
                    TreeName = tree
                }).ExecuteCommand();
            }

            // 再判断park - id是否存在
            if (db.Queryable<park>().Where(it => it.ParkName == park).ToList().Count == 0)
            {
                db.Insertable(new park()
                {
                    ParkName = park
                }).ExecuteCommand();
            }

            // 判断映射是否存在
            var temp1 = db.Queryable<tree>().Where(it => it.TreeName == tree).ToList();
            int treeId = temp1[0].TreeId;
            var temp2 = db.Queryable<park>().Where(it => it.ParkName == park).ToList();
            int parkId = temp2[0].ParkId;
            if (db.Queryable<park_tree>().Where(it => it.TreeId == treeId && it.ParkId == parkId).ToList().Count == 0)
            {
                db.Insertable(new park_tree()
                {
                    ParkId = parkId,
                    TreeId = treeId
                }).ExecuteCommand();
            }
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
}